package com.zhuchaooasystem.ui.home.fragment.oa.record;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.AudioInfo;
import com.zhuchaooasystem.libmp3lame.Mp3EncodeClient;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.TakeRecordContract;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.TakeRecordPresenter;
import com.zhuchaooasystem.utils.CalendarUtils;
import com.zhuchaooasystem.utils.FileUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TakeRecordActivity extends BaseActivity<TakeRecordPresenter> implements TakeRecordContract.View {

    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    @BindView(R.id.act_take_record_txt_desc)
    TextView txt_desc;
    @BindView(R.id.act_take_record_iv_control)
    ImageView iv_control;
    @BindView(R.id.act_take_record_txt_time)
    TextView txt_time;

    //----
    private Mp3EncodeClient mp3EncodeClient;
    private int time;
    private String path;
    private boolean stateStart;
    private int tag_pause;
    private Handler handlerTimer = new Handler();

    @Override
    protected int getLayout() {
        return R.layout.activity_take_record;
    }

    @Override
    protected TakeRecordPresenter getPresenter() {
        return new TakeRecordPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        stateStart = false;
        mPresenter.checkCameraPermission();
        mp3EncodeClient = new Mp3EncodeClient();
    }

    @Override
    protected void initView() {
        txt_title.setText(getString(R.string.actionbar_title_take_record));
        iv_back.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initDataAndLoadData() {
    }


    @OnClick({R.id.actionbar_iv_back, R.id.act_take_record_iv_control})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                if (stateStart) {
                    mPresenter.showDialog();
                } else {
                    finish();
                }
                break;
            //录音
            case R.id.act_take_record_iv_control:
                //录音权限
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    //请求权限
                    requestPermission(new String[]{Manifest.permission.RECORD_AUDIO}, Key.RECORD_AUDIO);
                } else {
                    setOnControl();
                }
                break;

        }
    }

    private void setOnControl() {
        if (stateStart) {
            stateStart = false;
            tag_pause = 1;
            mp3EncodeClient.stop();
            List<AudioInfo> audioInfoList = new ArrayList<>();
            audioInfoList.add(new AudioInfo(path, CalendarUtils.duration2timeString(((1800 - time)))));
            RxBus.get().post("takeRecord", new BaseEvent<>(audioInfoList));
            finish();
        } else {
            //----是否能进行录音
            if (mPresenter.checkEnviroment()) {
                stateStart = true;
                txt_time.setVisibility(View.VISIBLE);
                iv_control.setImageResource(R.drawable.ic_take_record_start);
                txt_desc.setText("请点击结束录音");
                path = FileUtils.createImageFile(Key.PATH_LOCAL_RECORDS, CalendarUtils.getNow("yyyyMMddHHmmss"), ".mp3").getPath();
                mp3EncodeClient.start(path);
                time = 1800;
                tag_pause = 0;
                handlerTimer.postDelayed(run, 1000);
            }
        }
    }


    private Runnable run = new Runnable() {
        @Override
        public void run() {
            if (tag_pause == 1) {
                handlerTimer.removeCallbacks(run);
            } else {
                time -= 1;
                if (time == -1) {
                    stateStart = false;
                    tag_pause = 1;
                    mp3EncodeClient.stop();
                    List<AudioInfo> audioInfoList = new ArrayList<>();
                    audioInfoList.add(new AudioInfo(path, CalendarUtils.duration2timeString(((1800 - time)))));
                    RxBus.get().post("takeRecord", new BaseEvent<>(audioInfoList));
                    finish();
                } else {
                    if (null != txt_time) {
                        txt_time.setText(CalendarUtils.duration2timeString((time)));
                    }
                    handlerTimer.postDelayed(run, 1000);
                }
            }
        }
    };

    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case Key.RECORD_AUDIO:
                setOnControl();
                break;
        }
    }

    /**
     * 权限失败回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_UP) {
            if (stateStart) {
                mPresenter.showDialog();
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    public void exit() {
        tag_pause = 1;
        mp3EncodeClient.stop();
        stateStart = false;
        finish();
    }
}
